package cn.com.zero.common.auth.security.listener;

import cn.com.zero.common.auth.security.service.AbstractLoginAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description 用户登录认证失败的事件监听器
 * @createTime 2023/3/27 13:59
 */
@Component
public class LoginFailureEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private AbstractLoginAuthenticationService loginAuthenticationService;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        // 当登录用户名或者密码不正确、手机号不正确会进入此方法，账户锁定、手机号的验证码不正确等不进入此方法
        Authentication authentication = event.getAuthentication();
        String userPrinciple = authentication.getName();

        // 登录失败监听器处理。登录失败后，添加登录失败日志、统计失败次数，判定是否用户已被锁定等
        loginAuthenticationService.loginFailureListenerProcess(userPrinciple);
    }

    @Autowired
    public void setLoginAuthenticationService(AbstractLoginAuthenticationService loginAuthenticationService) {
        this.loginAuthenticationService = loginAuthenticationService;
    }

}
